package cn.com.mds.common.db;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import cn.com.mds.service.impl.UserServiceImpl;

public class DataSourceAspect {

	public void before(JoinPoint point) {
		Object target = point.getTarget();
		String method = point.getSignature().getName();

		Class<?>[] classz = target.getClass().getInterfaces();
		Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		try {
			Method m = classz[0].getMethod(method, parameterTypes);
			if (m != null && m.isAnnotationPresent(DataSource.class)) {
				DataSource data = m.getAnnotation(DataSource.class);
				DynamicDataSourceHolder.putDataSource(data.value());
				System.out.println("当前注解的数据库：" + data.value());
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void main(String[] args) {
		 Method[] methods = UserServiceImpl.class.getMethods();  
         
	        for (Method method : methods) {  
	            Annotation[] annotations = method.getAnnotations();  
	            for (Annotation annotation : annotations) {  
	                // 获取注解的具体类型  
	                Class<? extends Annotation> annotationType = annotation.annotationType();  
	                if (DataSource.class == annotationType) {  
	                    System.out.println(method.getName()+"()\t" + DataSource.class.getName());  
	                      
	                    // 打印出java.lang.annotation.Annotation，注解类其实都实现了Annotation这个接口  
	                    Class<?>[] interfaces = DataSource.class.getInterfaces();  
	                    System.out.println(interfaces[0].getName());  
	                }  
	            }  
	        }  
	}
	
}
